package com.szh.htmltopdf;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.junit.jupiter.api.Test;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * base64 -> MultipartFile
 */
public class Base64MultipartFile {

    @Test
    public  void test() {
        Image bufferedImage = ImgUtil.toImage(FileUtil.readString(ResourceUtil.getResource("base64.txt"), StandardCharsets.UTF_8));
        String fileFullPath =tempDir()+System.currentTimeMillis()+".jpg";
        File file = FileUtil.touch(fileFullPath);
        ImgUtil.write(bufferedImage,file);

        MultipartFile multipartFile = getMultipartFile(file);
        
    }

    public static MultipartFile getMultipartFile(File file) {
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;

        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new CommonsMultipartFile(createFileItem(file,file.getName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }

    private String tempDir(){
        if (FileUtil.isWindows()){
            return "D:/";
        }
        return "/tmp/";
    }
    public static FileItem createFileItem(File file, String fileName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("file", "text/plain", false,fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
